package com.demo.studentmanager.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.demo.studentmanager.dto.LeaveAddDto;
import com.demo.studentmanager.dto.LeaveAuditListDto;
import com.demo.studentmanager.dto.LeaveUpdDto;
import com.demo.studentmanager.entity.LeaveAudit;
import com.demo.studentmanager.result.ResultCode;
import com.demo.studentmanager.service.impl.LeaveAuditServiceImpl;
import com.demo.studentmanager.service.impl.StudentServiceImpl;
import com.demo.studentmanager.service.impl.TeacherServiceImpl;
import com.demo.studentmanager.util.CheckEntityUtil;
import com.demo.studentmanager.vo.LeaveAuditVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Date;

/**
 * @author lzx
 * leave表的controller
 */

@RestController
@Api(tags = "请假模块")
@RequestMapping(("/leave"))
public class LeaveAuditController {

    @Resource
    LeaveAuditServiceImpl leaveService;

    @Resource
    private StudentServiceImpl studentService;

    @Resource
    private TeacherServiceImpl teacherService;

    @RequiresAuthentication
    @GetMapping
    @ApiOperation(value = "查看请假信息")
    IPage<LeaveAuditVo> getLeaveList(@Validated LeaveAuditListDto auditDto) {
        return leaveService.getLeaveStu(auditDto);
    }

    @RequiresRoles(value={"teacher","admin"},logical= Logical.OR)
    @PutMapping
    @ApiOperation(value = "批改请假信息")
    void updateLeave(@Validated LeaveUpdDto upDto) {
        LeaveAudit leaveAuditStu = CheckEntityUtil.isNullById(upDto.getId(), leaveService, ResultCode.LEAVE_NOT_EXIST);
        CheckEntityUtil.isNullById(upDto.getTno(), teacherService, ResultCode.TEACHER_ACCOUNT_NOT_EXIST);
        leaveAuditStu.setTime(new Date());
        upDto.convertToEntity(leaveAuditStu);

        leaveService.updateById(leaveAuditStu);
    }

    @RequiresAuthentication
    @PostMapping
    @ApiOperation(value = "新增请假信息")
    void addLeave(@Validated LeaveAddDto addDto) {
        CheckEntityUtil.isNotNullById(addDto.getId(), leaveService, ResultCode.LEAVE_EXIST);
        CheckEntityUtil.isNullById(addDto.getSno(), studentService, ResultCode.STUDENT_NOT_EXIST);
        LeaveAudit leaveAudit = new LeaveAudit();
        addDto.convertToEntity(leaveAudit);

        leaveService.save(leaveAudit);
    }

    @RequiresRoles(value={"teacher","admin"},logical= Logical.OR)
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除请假信息")
    public void deleteLeave(@NotNull @PathVariable  String id) {
        CheckEntityUtil.isNullById(id, leaveService, ResultCode.USER_ACCOUNT_NOT_EXIST);

        leaveService.removeById(id);
    }

}
